/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

package com.je.bpm.engine.impl.cmd;

import com.google.common.base.Strings;
import com.je.bpm.core.model.BpmnModel;
import com.je.bpm.core.model.FlowElement;
import com.je.bpm.core.model.task.KaiteCounterSignUserTask;
import com.je.bpm.core.model.task.KaiteMultiUserTask;
import com.je.bpm.engine.RepositoryService;
import com.je.bpm.engine.delegate.DelegateExecution;
import com.je.bpm.engine.impl.bpmn.behavior.MultiInstanceActivityBehavior;
import com.je.bpm.engine.impl.interceptor.Command;
import com.je.bpm.engine.impl.interceptor.CommandContext;
import com.je.bpm.engine.impl.persistence.entity.TaskEntity;

import java.io.Serializable;
import java.util.Map;

/**
 * 获取节点信息
 */
public class GetSubmitDirectlyCmd implements Command<Boolean>, Serializable {

    private static final long serialVersionUID = 1L;
    protected String executionId;
    protected String taskId;
    protected Map<String, Object> bean;
    protected String pdid;

    public GetSubmitDirectlyCmd(String pdid, String taskId) {
        this.taskId = taskId;
        this.pdid = pdid;
    }

    @Override
    public Boolean execute(CommandContext commandContext) {
        if (Strings.isNullOrEmpty(taskId)) {
            return false;
        }
        TaskEntity task = commandContext.getTaskEntityManager().findById(taskId);
        if (task == null) {
            return false;
        }
        if (task.isSuspended()) {
            return false;
        }
        return getSubmitDirectly(commandContext, task);
    }

    private Boolean getSubmitDirectly(CommandContext commandContext, TaskEntity task) {
        RepositoryService repositoryService = commandContext.getProcessEngineConfiguration().getRepositoryService();
        BpmnModel bpmnModel = repositoryService.getBpmnModel(task.getProcessDefinitionId());
        FlowElement taskFlowElement = bpmnModel.getFlowElement(task.getTaskDefinitionKey());
        //多人节点(不是最后一人)\会签节点,可以直接提交不用选人
        if (taskFlowElement instanceof KaiteMultiUserTask) {
            if (((KaiteMultiUserTask) taskFlowElement).getLoopCharacteristics().isSequential()) {
                DelegateExecution multiInstanceRootExecution = getMultiInstanceRootExecution(task.getExecution());
                int loopCounter = getLoopVariable(task.getExecution(), "loopCounter") + 1;
                int nrOfInstances = getLoopVariable(multiInstanceRootExecution, MultiInstanceActivityBehavior.NUMBER_OF_INSTANCES);
                if (loopCounter >= nrOfInstances) {
                    return false;
                } else {
                    return true;
                }
            } else {
                int nrOfCompletedInstances = getLoopVariable(task.getExecution(), MultiInstanceActivityBehavior.NUMBER_OF_COMPLETED_INSTANCES) + 1;
                int nrOfInstances = getLoopVariable(task.getExecution(), MultiInstanceActivityBehavior.NUMBER_OF_INSTANCES);
                if (nrOfCompletedInstances >= nrOfInstances) {
                    return false;
                } else {
                    return true;
                }
            }
        } else if (taskFlowElement instanceof KaiteCounterSignUserTask) {
            return true;
        } else {
            return false;
        }
    }

    protected Integer getLoopVariable(DelegateExecution execution, String variableName) {
        Object value = execution.getVariableLocal(variableName);
        DelegateExecution parent = execution.getParent();
        while (value == null && parent != null) {
            value = parent.getVariableLocal(variableName);
            parent = parent.getParent();
        }
        return (Integer) (value != null ? value : 0);
    }

    protected DelegateExecution getMultiInstanceRootExecution(DelegateExecution executionEntity) {
        DelegateExecution multiInstanceRootExecution = null;
        DelegateExecution currentExecution = executionEntity;
        while (currentExecution != null && multiInstanceRootExecution == null && currentExecution.getParent() != null) {
            if (currentExecution.isMultiInstanceRoot()) {
                multiInstanceRootExecution = currentExecution;
            } else {
                currentExecution = currentExecution.getParent();
            }
        }
        return multiInstanceRootExecution;
    }

}
